import React, { PureComponent } from 'react';
import { Empty, Checkbox, Tag, Carousel, notification,Modal } from 'antd';
import StructureTree from "../forms/structureTree"
import { connect } from 'dva';
import { worker } from "../../utils/worker"
import {cloneDeep} from "lodash"
import "../../Common.less"
import "./index.less"
class structureSelect extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            expandedKeys: [],
            selectedKeys: [],
            treeData: [],
            attrDictList: [],
            loading: true,
            rightStructures: [],
            selectResults: [],
            currentComponentInfo: []
        }
        this.onSelect = this.onSelect.bind(this)
        this.selectStructure = this.selectStructure.bind(this)
        this.onConfirm = this.onConfirm.bind(this)
        this.getDictName = this.getDictName.bind(this)
    }

    onConfirm(params = {}) {
        let { structureTree } = this.props;
        let { selectResults, extra } = this.state;
        return new Promise(async (resolve, reject) => {
            let prestr = extra.type == "top" ? "topStructureComponentUnit" : "botStructureComponentUnit";
            let pre = extra.type == "bottom" ? "botStructureDirec" : "topStructureDirec";
            if (extra.operateType) {
                if (extra.operateType == "add") {
                    this.props.addDefinitionInstance({
                        operateType: "add",
                        selectionOrSpanIds: extra.selectionOrSpanIds && extra.selectionOrSpanIds.length ? Array.from(new Set(extra.selectionOrSpanIds)) : [extra.sid],
                        definitionIds: selectResults && selectResults.length ? selectResults.map(item => item.id) : [],
                        bridgeId: extra.bridgeId,
                        type: extra.type
                    }, async res => {
                        if (res && res.length) {
                            let arr = []
                            const len = res.length;
                            for (let i = 0; i < len; i++) {
                                let unit = res[i];
                                if (unit.data && unit.data.length) {
                                    const len2 = unit.data.length
                                    for (let j = 0; j < len2; j++) {
                                        let obj = unit.data[j];
                                        let { definitionInstances, selectionOrSpanId } = obj;
                                        if (definitionInstances && definitionInstances.length) {
                                            const len3 = definitionInstances.length
                                            for (let k = 0; k < len3; k++) {
                                                let item = definitionInstances[k];
                                                const obj2 = await worker.getTreeNode(structureTree, item.definitionTreeId)
                                                item.title = obj2.title + ":" + item.instanceName;
                                                item.key = prestr + item.id;
                                                item.type = extra.type;
                                                item.eventType = prestr
                                                item.eventKey = prestr
                                                item.checkable = true
                                                item.selectable = true
                                                item.isLeaf = true
                                                arr.push(item.id)
                                            }
                                        }
                                        if (extra.type == "top") {
                                            this.props.treeContext.updateTreeNode(pre + selectionOrSpanId, definitionInstances);
                                        } else {
                                            this.props.treeContext.insertTreeNode(pre + selectionOrSpanId, definitionInstances);
                                        }
                                    }
                                }

                            }
                            let res2 = await this.props.getBottomProperty({
                                definitionIds: selectResults && selectResults.length ? selectResults.map(item => item.id) : [],
                                definitionInstanceIds: arr,
                                type: extra.type
                            })
                            if (res2 && res2.length) {
                                resolve()
                                if (params.onSuccess) {
                                    params.onSuccess("success");
                                }
                                this.props.modalContext.updateModal({
                                    visible: true,
                                    title: "自定义属性编辑",
                                    event: { code: "cusTable",width:1200 },
                                    extra: {
                                        designedStructures: res2,
                                        type: extra.type
                                    }
                                })

                            } else {
                                notification.warn({ message: "该构件下暂无计算属性!" })
                                reject("err")
                            }
                        }


                        this.props.formContext.refresh()

                    }, err => {
                        reject()
                        if (params.onError) {
                            params.onError("error");
                        }
                    })
                }else{
                    Modal.confirm({
                        title: "提示",
                        centered:true,
                        content: "如果之前绑定了构件，您当前的操作会替换掉之前设置的全部构件。【确定】继续操作，【取消】返回修改",
                        okText:"确定",
                    cancelText:"取消",
                        onOk:()=>{
                             if (extra.operateType == "update") {
                    
                                this.props.replaceDefinitionInstance({
                                    bridgeId: extra.bridgeId,
                                    operateType: "update",
                                    definitionInstanceIds: extra.definitionIds,
                                    definitionIds: selectResults && selectResults.length ? selectResults.map(item => item.id) : [],
                                    selectionOrSpanIds: !(extra.sid instanceof Array) ? [extra.sid] : Array.from(new Set([...extra.sid])),
                                    type: extra.type
                                }, async res => {
                                    if (extra.type == "bottom") {
                                        if (extra.definitionIds && extra.definitionIds.length) {
                                            const len = extra.definitionIds.length;
                                            for (let i = 0; i < len; i++) {
                                                const item = extra.definitionIds[i];
                                                this.props.treeContext.removeTreeNode(prestr + item)
                                            }
                                        }
            
                                    }
                                    if (res && res.length) {
                                        const len = res.length;
                                        let arr = []
                                        for (let i = 0; i < len; i++) {
                                            let unit = res[i];
            
                                            if (unit.data && unit.data.length) {
                                                const len2 = unit.data.length
                                                for (let j = 0; j < len2; j++) {
                                                    let obj = unit.data[j];
                                                    let { definitionInstances, selectionOrSpanId } = obj;
                                                    if (definitionInstances && definitionInstances.length) {
                                                        const len3 = definitionInstances.length
                                                        for (let k = 0; k < len3; k++) {
                                                            let item = definitionInstances[k];
                                                            const obj2 = await worker.getTreeNode(structureTree, item.definitionTreeId)
                                                            item.title = obj2.title + ":" + item.instanceName;
                                                            item.key = prestr + item.id;
                                                            item.type = extra.type;
                                                            item.eventType = prestr
                                                            item.eventKey = prestr
                                                            item.checkable = true
                                                            item.selectable = true
                                                            item.isLeaf = true
                                                            arr.push(item.id)
                                                        }
                                                        if (extra.type == "top") {
                                                            this.props.treeContext.updateTreeNode(pre + selectionOrSpanId, definitionInstances)
                                                        } else {
                                                            this.props.treeContext.insertTreeNode(pre + selectionOrSpanId, definitionInstances)
                                                        }
            
                                                    }
                                                }
                                            }
            
            
                                        }
                                        let res2 = await this.props.getBottomProperty({
                                            definitionIds: selectResults && selectResults.length ? selectResults.map(item => item.id) : [],
                                            definitionInstanceIds: arr,
                                            type: extra.type
                                        })
                                        if (res2 && res2.length) {
                                            resolve()
                                            if (params.onSuccess) {
                                                params.onSuccess("success");
                                            }
                                            this.props.modalContext.updateModal({
                                                visible: true,
                                                title: "自定义属性编辑",
                                                event: { code: "cusTable",width:1200 },
                                                extra: {
                                                    designedStructures: res2,
                                                    type: extra.type
                                                }
                                            })
            
                                        } else {
                                            notification.warn({ message: "该构件下暂无计算属性!" })
                                            reject("err")
                                        }
                                    }
            
                                    this.props.formContext.refresh()
            
                                    // if (this.props.goInnerPage) {
                                    //     this.props.goInnerPage(null, 'results', '操作成功')
                                    // }
                                }, err => {
                                    reject()
                                    if (params.onError) {
                                        params.onError("error");
                                    }
                                })
                            } else if (extra.operateType == "cusProps") {
                                let arr = [];
                                this.props.addDefinitionInstance({
                                    operateType: "cover",
                                    selectionOrSpanIds: extra.selectionOrSpanIds && extra.selectionOrSpanIds.length ? Array.from(new Set(extra.selectionOrSpanIds)) : [],
                                    definitionIds: selectResults && selectResults.length ? selectResults.map(item => item.id) : [],
                                    bridgeId: extra.bridgeId,
                                    type: extra.type
                                }, async res => {
                                    if (res && res.length) {
                                        const len = res.length;
                                        for (let i = 0; i < len; i++) {
                                            let obj = res[i];
                                            if (obj.data && obj.data.length) {
                                                const len2 = obj.data.length
                                                for (let i = 0; i < len2; i++) {
                                                    let unit = obj.data[i];
                                                    let { definitionInstances, selectionOrSpanId } = unit;
                                                    if (definitionInstances && definitionInstances.length) {
                                                        const len3 = definitionInstances.length
                                                        for (let i = 0; i < len3; i++) {
                                                            let item = definitionInstances[i];
                                                            const obj2 = await worker.getTreeNode(structureTree, item.definitionTreeId)
                                                            item.title = obj2.title + ":" + item.instanceName;
                                                            item.key = prestr + item.id;
                                                            item.type = extra.type;
                                                            item.eventType = prestr
                                                            item.eventKey = prestr
                                                            item.checkable = true
                                                            item.selectable = true
                                                            item.isLeaf = true
                                                            arr.push(item.id)
                                                        }
            
                                                    }
                                                    this.props.treeContext.updateTreeNode(pre + selectionOrSpanId, definitionInstances)
                                                }
                                            }
            
                                        }
            
                                        let res2 = await this.props.getBottomProperty({
                                            definitionIds: selectResults && selectResults.length ? selectResults.map(item => item.id) : [],
                                            definitionInstanceIds: arr,
                                            type: extra.type
                                        })
                                        if (res2 && res2.length) {
                                            resolve()
                                            if (params.onSuccess) {
                                                params.onSuccess("success");
                                            }
                                            this.props.modalContext.updateModal({
                                                visible: true,
                                                title: "自定义属性编辑",
                                                event: { code: "cusTable",width:1200 },
                                                extra: {
                                                    designedStructures: res2,
                                                    type: extra.type
                                                }
                                            })
            
                                        } else {
                                            notification.warn({ message: "该构件下暂无计算属性!" })
                                            reject("err")
                                        }
            
                                    }
                                }, err => {
                                    if (params.onError) {
                                        params.onError("err");
                                    }
                                    reject()
                                })
            
                            }
                        },
                        onCancel() {
                            if (params.onError) {
                                params.onError("err");
                            }
                            reject("err")
                        }
                    })
                } 
            } else {
                Modal.confirm({
                    title: "提示",
                    content: "如果之前绑定了构件，您当前的操作会替换掉之前设置的全部构件。【确定】继续操作，【取消】返回修改",
                    okText:"确定",
                    cancelText:"取消",
                    onOk:()=>{
                        this.props.addDefinitionInstance({
                            operateType: extra.operateType || "cover",
                            selectionOrSpanIds: extra.selectionOrSpanIds && extra.selectionOrSpanIds.length ? Array.from(new Set(extra.selectionOrSpanIds)) : [],
                            definitionIds: selectResults && selectResults.length ? selectResults.map(item => item.id) : [],
                            bridgeId: extra.bridgeId,
                            type: extra.type
                        }, async res => {
                            if (res && res.length) {
                                const len = res.length;
                                for (let i = 0; i < len; i++) {
                                    let obj = res[i];
                                    if (obj.data && obj.data.length) {
                                        const len2 = obj.data.length
                                        for (let i = 0; i < len2; i++) {
                                            let unit = obj.data[i];
                                            let { definitionInstances, selectionOrSpanId } = unit;
                                            if (definitionInstances && definitionInstances.length) {
                                                const len3 = definitionInstances.length
                                                for (let i = 0; i < len3; i++) {
                                                    let item = definitionInstances[i];
                                                    const obj2 = await worker.getTreeNode(structureTree, item.definitionTreeId)
                                                    item.title = obj2.title + ":" + item.instanceName;
                                                    item.key = prestr + item.id;
                                                    item.type = extra.type;
                                                    item.eventType = prestr
                                                    item.eventKey = prestr
                                                    item.checkable = true
                                                    item.selectable = true
                                                    item.isLeaf = true
                                                }
                                            }
                                            this.props.treeContext.updateTreeNode(pre + selectionOrSpanId, definitionInstances)
                                        }
                                    }
        
                                }
                                resolve()
                                if (params.onSuccess) {
                                    params.onSuccess("success");
                                }
                            }
        
                        }, err => {
                            if (params.onError) {
                                params.onError("err");
                            }
                            reject()
                        })
                    },
                    onCancel() {
                        if (params.onError) {
                            params.onError("err");
                        }
                        reject("err")
                    }
                })
               
            }


        })
    }
    getDictName(list, attrEnName) {
        let obj = list.find(item => item.id == attrEnName);
        return obj ? obj.dictLabel : ""
    }
    async getRightStructures(data, path) {
        let { extra, selectedKeys, treeData } = this.state;
        this.setState({
            loading: true
        })
        const {bridgeId,spanType,tid,nodeType}=extra;
        let res = await this.props.getDefinitionList({bridgeId,spanType,definitionTreeId:tid,nodeType})
        
        if (res && res.length) {
            const len = res.length;
            for (let i = 0; i < len; i++) {
                let item = res[i];
                item.wholeName = await worker.findNodePathByKey(treeData, item.definitionTreeId)
            }
            selectedKeys = res && res.length ? [res[0].definitionTreeId + ''] : []
            this.setState({
                loading: false,
                selectedKeys,
            })
        } else {
            this.setState({
                loading: false,
            })
        }
        return res
    }
    async getStructureInstances(data, level) {
        let { extra, selectResults, treeData } = this.state;
        let res = await this.props.getDefinitionList(data ? data : extra)
        if (res && res && res.length) {
            const len = res.length
            for (let i = 0; i < len; i++) {
                let item = res[i];
                item.definitionTreeLevel = level;
                item.wholeName = await worker.findNodePathByKey(treeData, item.definitionTreeId)
                const len2 = selectResults.length
                for (let j = 0; j < len2; j++) {
                    let item2 = selectResults[j];
                    if (item.id == item2.id) {
                        item.checked = true
                    }

                }

            }
            this.setState({
                rightStructures: res
            })
        } else {
            this.setState({
                rightStructures: []
            })
        }

    }
    async onSelect(keys, e) {
        let { extra } = this.state;
        let { level, id,title } = e.node.props.dataRef;
        this.setState({
            currentComponentInfo:[],
            selectedKeys: keys,
            title
        })
        // if (level - 3 >= 0) {
        this.getStructureInstances({ nodeType: extra.nodeType, definitionTreeId: id,spanType:extra.spanType }, level)

        // }
    }

    async componentWillMount() {
        let { extra } = this.props;
        let res = await this.props.getStructureTree({ ...extra })
        let resc = cloneDeep(await worker.loopTreeNode7(res, null, true))
        let resc2 = await worker.loopTreeNode7(resc,extra.spanType?(extra.spanType=="A"?[extra.spanType]:[extra.spanType,"F"]):[], true)
        if (resc2) {
            this.setState({
                extra,
                expandedKeys: resc2.map(item => item.key),
                treeData: resc2
            })
            let res2 = await this.getRightStructures({ ids: extra.definitionIds, ...extra })
            if (!extra.operateType || (extra.operateType && extra.operateType != "add")) {
                if (res2 && res2.length) {
                    const len = res2.length;
                    for (let i = 0; i < len; i++) {
                        let item = res2[i];
                        if (extra.definitionTemps && extra.definitionTemps.length) {
                            const len2 = extra.definitionTemps.length
                            for (let j = 0; j < len2; j++) {
                                let item2 = extra.definitionTemps[j];
                                if (item.id == item2) {
                                    item.checked = true
                                }
                            }
                        }
                    }
                }
                let arr = [];
                if (extra.originalData && extra.originalData.length) {
                    const len3 = extra.originalData.length
                    for (let i = 0; i < len3; i++) {
                        let item = extra.originalData[i];
                        let tname = await worker.findNodePathByKey(res, item.definitionTreeId)
                        if (!arr.find(obj => obj.id == item.definitionId)) {
                            arr.push({
                                id: item.definitionId,
                                wholeName: tname.slice(0, tname.length)
                                
                            })
                        }
                    }
                }
                // console.log(extra.definitionTemps.map(item => item + ''))
                this.setState({
                    rightStructures: res2 && res2.length ? res2 : [],
                    selectResults: Array.from(new Set(arr)),
                    selectedKeys: extra.definitionTreeIds && extra.definitionTreeIds.length ? extra.definitionTreeIds.map(item => item + '') : []
                })
            } else {
                this.setState({
                    rightStructures: res2 && res2.length ? res2 : [],
                })
            }
        }

    }
    async componentDidMount() {
        if (this.props.onLoaded) {
            this.props.onLoaded(this);
        }
        const { dictlist, extra } = this.props;
        let res = await this.props.cusPropsList()
        let data = await this.props.definitionTreeAttrList()

        this.setState({
            unitlist: dictlist.filter(item => item.dictType == "unit"),
            propsList: res,
            attrDictList: data
        })
    }

    async selectStructure(e, item) {
        e.preventDefault()
        let { selectResults, rightStructures, treeData, selectedKeys } = this.state;
        let definitionTreeId = rightStructures[0].definitionTreeId;
        let obj = await worker.getTreeNode(treeData, definitionTreeId)
        selectedKeys = [obj.id + '']

        if (obj) {
            obj.selected = true;
        }
        this.setState({
            selectedKeys,
            treeData
        })

        item.checked = !item.checked;
        item.wholeName = await worker.findNodePathByKey(treeData, definitionTreeId)
        this.setState({
            rightStructures: [...this.state.rightStructures]
        })
        if (item.checked) {
            if (!selectResults.find(item2 => item2.id == item.id)) {
                selectResults.push(item)
            }
        } else {
            let index = selectResults.findIndex(item2 => item2.id == item.id)

            selectResults.splice(index, 1)
            console.log(index, selectResults)
        }
        if (!item.extraData) {
            let res = await this.props.getDefinitionDetail({ id: item.id })
            if (res) {
                item.extraData = res
            }
            this.setState({
                currentComponentInfo: res.definitionComponents,
                selectResults: [...selectResults]
            })
        } else {
            this.setState({
                currentComponentInfo: item.extraData.definitionComponents,
                selectResults: [...selectResults]
            })
        }


    }
    render() {
        let { treeData, expandedKeys, rightStructures, currentComponentInfo, selectResults, selectedKeys, unitlist, loading } = this.state
        return (
            <div className="absMiddle structureSelect">
                <div className="absMiddle selectMain">
                    <StructureTree treeData={treeData} selectedKeys={selectedKeys} expandedKeys={expandedKeys} onSelect={this.onSelect} onLoaded={(context) => {
                        this.setState({
                            structureTreeContext: context
                        })
                    }}></StructureTree>
                    <div className="checkBoxArea absMiddle">
                        <div className="title absMiddle">
                            选择构件
                        </div>

                        <div className="absMiddle checkBoxmain">
                            {
                                !loading && rightStructures && rightStructures.length ? rightStructures.map((item, index) => {
                                    return (
                                        <div key={'struc' + index}>
                                            <Checkbox onClick={e => this.selectStructure(e, item)} checked={item.checked}></Checkbox>
                                            <div >
                                                <div>
                                                    <Carousel dots>
                                                        <div><div style={{ backgroundImage: `url(${item.imgPath ? item.imgPath : 'static/svg/1.svg'})`, backgroundSize: 'cover', backgroundPosition: 'center center' }}></div></div>
                                                    </Carousel>
                                                </div>
                                                <div>{item.definitionName}</div>
                                            </div>

                                        </div>
                                    )
                                }) : undefined
                            }
                            {
                                !loading && (!rightStructures || !rightStructures.length) ? <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}></Empty> : undefined
                            }

                        </div>
                    </div>
                    <div className="structureInfo absMiddle">
                        {
                            currentComponentInfo && currentComponentInfo.length ? currentComponentInfo.map((item, index) => {
                                return (
                                    <div key={item.id + item.createTime} className="absMiddle">
                                        <div className="title absMiddle">{item.componentName}</div>
                                        {
                                            item.definitionComponentProperties && item.definitionComponentProperties.length ? item.definitionComponentProperties.map((item2, index2) => {
                                                return <div key={item.name + index2} className="absMiddle">
                                                    {
                                                        item2.definitionComponentProperty && item2.definitionComponentProperty.length ? item2.definitionComponentProperty.map((item3, index3) => {
                                                            return (
                                                                <div key={item.id + index3}>{item3.name + '(' + this.getDictName(unitlist, item3.unit) + ')' + ':' + item3.defaultValue}</div>
                                                            )
                                                        }) : null
                                                    }

                                                </div>
                                            }) : null
                                        }

                                    </div>
                                )
                            }) : null
                        }

                    </div>
                </div>
                <div className="absMiddle selectResults">
                    <div className="absMiddle">已选:</div>
                    <div className="absMiddle">
                        {
                            selectResults && selectResults.length ? selectResults.map((item, index) => {
                                return (
                                    <Tag
                                        key={item.id + item.wholeName}
                                        closable
                                        onClose={e => {
                                            e.preventDefault();

                                            let obj = rightStructures.find(item2 => item2.id == item.id)
                                            // debugger
                                            if (obj) {
                                                obj.checked = obj.checked ? false : true;
                                            }

                                            selectResults.splice(index, 1)
                                            this.setState({
                                                selectResults: [...selectResults],
                                                rightStructures
                                            })
                                        }}
                                    >
                                        {item.wholeName}
                                    </Tag>
                                )
                            }) : null
                        }

                    </div>
                </div>
            </div>
        )
    }
}
export default connect(
    ({ dict: { structureTree, dictlist } }) => ({ structureTree, dictlist }),
    dispatch => ({
        addDefinitionInstance: (values, onSuccess, onError) => dispatch({
            type: 'structure/addDefinitionInstance',
            payload: {
                values,
                onSuccess,
                onError
            }
        }),
        cusPropsList: (values) => dispatch({
            type: 'cusProps/cusPropsList',
            payload: values
        }),
        setDesignedStructures: (values, onSuccess, onError) => dispatch({
            type: 'structure/setDesignedStructures',
            payload: {
                values,
                onSuccess,
                onError
            }
        }),
        replaceDefinitionInstance: (values, onSuccess, onError) => dispatch({
            type: 'structure/replaceDefinitionInstance',
            payload: {
                values,
                onSuccess,
                onError
            }
        }),
        definitionTreeAttrList: (values) => dispatch({
            type: 'structure/definitionTreeAttrList',
            payload: values
        }),
        getStructureTree: (values) => dispatch({
            type: 'structure/getStructureTree',
            payload: values
        }),
        getDefinitionList: (values) => dispatch({
            type: 'structure/getDefinitionList',
            payload: values
        }),
        getTopStructureInstance: (values) => dispatch({
            type: 'structure/getTopStructureInstance',
            payload: values
        }),
        getDefinitionDetail: (values) => dispatch({
            type: 'structure/getDefinitionDetail',
            payload: values
        }),
        getBottomProperty: (values) => dispatch({
            type: 'structure/getBottomProperty',
            payload: values
        }),
    })
)(structureSelect);